<template>
    <div class="datas">
        <h1>个人数据集</h1>
        <div class="btns">
            <el-button-group>
                <el-button type="danger" @click="deleteDataset()">删除</el-button>
                <el-button @click="downloadDataset()">下载条目ID</el-button>
                <el-button @click="downloadDataset()">修改数据集信息</el-button>
                <el-button type="success" @click="reflash()">刷新</el-button>
                <el-button type="warning" @click="createDataset()">新建数据集</el-button>
            </el-button-group>
        </div>
        <el-table @selection-change="handleSelectionChange" v-loading="loading" :data="tableData" tooltip-effect="dark"
            style="width: 100%" border>
            <el-table-column type="selection" width="100">
            </el-table-column>
            <el-table-column label="数据集ID" width="120">
                <template slot-scope="scope">{{ scope.row.dataset_id }}</template>
                <!-- 这里为什么必须用插槽呢？ -->
            </el-table-column>
            <el-table-column prop="dataset_name" label="数据集名称" width="120">
            </el-table-column>
            <el-table-column prop="comment" label="描述">
            </el-table-column>
            <el-table-column prop="create_time" label="创建时间">
            </el-table-column>
            <el-table-column prop="data_id" label="数据id">
            </el-table-column>
            <el-table-column prop="tot_num" label="总条目数">
            </el-table-column>
        </el-table>
        <div class="block">
            <el-pagination @current-change="pageChange" layout="prev, pager, next" :total="pagination.total">
            </el-pagination>
        </div>
        <el-dialog title="新建数据集" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
            <div v-loading="commitLoading">
                <div class="inpus">
                    <el-input class="diaInput" v-model="newDatas.dataset_name" placeholder="请输入数据集名称"></el-input>
                    <el-input class="diaInput" v-model="newDatas.comment" placeholder="请输入数据集描述"></el-input>
                </div>
                <div class="diaBtns">
                    <el-button @click="handleClose()">取 消</el-button>
                    <el-button type="primary" @click="commitDataset()">确 定</el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import Axios from 'axios';
export default {
    data() {
        return {
            showHiding: false,
            tableData: [
                // { ID: '123123', dataName: '氧化铝实验', description: 'a normal test!', createTime: '2022-10-4', totalSum: '123' },
                // { ID: '123123', dataName: '氧化铝实验', description: 'a normal test!', createTime: '2022-10-4', totalSum: '123' },
                // { ID: '123123', dataName: '氧化铝实验', description: 'a normal test!', createTime: '2022-10-4', totalSum: '123' },
                // { ID: '123123', dataName: '氧化铝实验', description: 'a normal test!', createTime: '2022-10-4', totalSum: '123' },
                // { ID: '123123', dataName: '氧化铝实验', description: 'a normal test!', createTime: '2022-10-4', totalSum: '123' },
                // { ID: '123123', dataName: '氧化铝实验', description: 'a normal test!', createTime: '2022-10-4', totalSum: '123' },
                // { ID: '123123', dataName: '氧化铝实验', description: 'a normal test!', createTime: '2022-10-4', totalSum: '123' },
                // { ID: '123123', dataName: '氧化铝实验', description: 'a normal test!', createTime: '2022-10-4', totalSum: '123' },
            ],
            pagination: {
                total: 1,
                page_size: 10,
                current_page: 1,
            },//分页参数
            commitLoading: false,
            loading: false,
            dialogVisible: false,
            newDatas: {
                user_id: undefined,
                dataset_name: '',
                comment: '',
                tot_num: 0,
                dataset_id: '',
                data_id: [],
            },
            deleteArr: [],//删除选中的数组
            downloadArr: [],//下载选中的数组
            userId:undefined,
        }
    },
    mounted() {
        let times = 0;
        this.loading = true;
        let getID =  setInterval(()=>{
            this.userId = localStorage.getItem('id');
            times++;
            if(this.userId !== "undefined"){
                clearInterval(getID);
                this.reflash();//获取页面数据
            }
            if(times>=5){
                clearInterval(getID);
                this.$message.error("获取数据失败！")
            }
        },500)
        //获取ID；
        
    },
    methods: {
        reflash() {
            this.loading = true
            let page = this.pagination.current_page - 1;
            let body = {
                "[]": {
                    "Ev_dataset": {
                        "delete_mark": 0,
                        "user_id": this.userId,
                    },
                    "page": page,
                    "count": 10,
                    "query": 2
                },
                "total@": "/[]/total"
            }
            Axios.post('http://c7.cabc.top:8222/api/v1.0/jwt/APIjson/get/', body)
                .then((res) => {
                    console.log(res);
                    this.loading = false;
                    if (res.data.code === "0") {
                        let arr = [];
                        this.pagination.total = res.data.data[Object.keys(res.data.data)[8]];
                        let data = res.data.data[Object.keys(res.data.data)[0]]
                        for (let i in data) {
                            data[i].Ev_dataset.data_id = data[i].Ev_dataset.data_id.toString()
                            arr.push(data[i].Ev_dataset)
                        }
                        this.tableData = arr;
                    } else {
                        this.$message.error('获取数据集出错！');
                    }
                }).catch((err) => {
                    this.loading = false;
                    console.log(err);
                    this.$message.error('获取数据集出错！');
                });
        },
        createDataset() {
            this.dialogVisible = true;
            function create_dataset_id(len) {
                const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890'
                const maxPos = chars.length
                let str = ''
                for (let i = 0; i < len; i++) {
                    str += chars.charAt(Math.floor(Math.random() * maxPos))
                }
                return str;
            }
            this.newDatas.dataset_id = create_dataset_id(8);
            // this.newDatas.user_id = localStorage.getItem('name').id
            this.newDatas.user_id = this.userId;// test
        },
        commitDataset() {
            this.commitLoading = true
            let body = {
                Ev_dataset: this.newDatas,
                tag: "Ev_dataset"
            }
            Axios.post('http://c7.cabc.top:8222/api/v1.0/jwt/APIjson/post/', body)
                .then((res) => {
                    this.commitLoading = false;
                    this.dialogVisible = false;
                    if (res.data.data.code === 200) {
                        this.$message.success('创建成功！')
                        this.reflash()
                    } else if (res.data.data.code == '500') {
                        this.$message.error(res.data.data.msg)
                    } else {
                        this.$message.error("创建失败！")
                    }

                }).catch((err) => {
                    this.commitLoading = false;
                    this.dialogVisible = false;
                    console.log(err);
                    this.$message.error('上传失败！')
                });
        },
        handleClose() {
            this.newDatas.dataset_name = '';
            this.newDatas.comment = '';
            this.dialogVisible = false
        },
        handleSelectionChange(val) {
            this.deleteArr = val;
            this.downloadArr = val;
        },
        deleteDataset() {
            for (let i in this.deleteArr) {
                let id = this.deleteArr[i].id;
                let body = {
                    Ev_dataset: {
                        id,
                        delete_mark: 1
                    },
                    tag: "Ev_dataset"
                }
                Axios.post("http://c7.cabc.top:8222/api/v1.0/jwt/APIjson/put/", body)
                    .then((res) => {
                        if (res.data.data.code === 200) {
                            this.$message.success(`id:${this.deleteArr[i].dataset_id}数据集删除成功！`)
                            this.reflash();
                        } else {
                            this.$message.error(res.data.data.msg)
                        }
                    }).catch((err) => {
                        console.log(err);
                        this.$message.error("删除失败！")
                    });
            }
        },
        downloadDataset() {
            //下载数据集
            if (this.downloadArr.length > 1) {
                this.$message.error("单次只能下载一个数据集")
                return
            } else if (this.downloadArr.length === 0) {
                this.$message.error("请选择你要下载的数据集")
                return
            } else {
                let id = this.downloadArr[0].id
                Axios.get(`http://c7.cabc.top:8222/api/v1.0/jwt/dataset/downloaddataset/?id=${id}`)
                    .then((res) => {
                        if(res.status === 200){
                            this.downloadByPeople(res.data)
                        }else{
                            this.$message.error("下载失败！")
                        }
                    }).catch((err) => {
                        console.log(err);
                        this.$message.error("下载失败！")
                    });
            }
        },
        pageChange(num) {
            this.pagination.current_page = num;
            this.reflash()
        },
        downloadByPeople(data) {
            const url = genUrl(data) //{}指的是表头，data是后台返回来的流数据
            const a = document.createElement('a')
            a.href = url
            a.download = `数据集文件.csv`
            a.click()
            window.URL.revokeObjectURL(url)

            // 获取导出链接
            function genUrl(encoded) {
                const dataBlob = new Blob([`\ufeff${encoded}`], {
                    type: 'text/plain;charset=utf-8'
                }) //返回的格式
                return window.URL.createObjectURL(dataBlob)
            }
        }

    }
}
</script>
<style scoped>
.datas {
    width: 90%;
    margin: 50px auto;
}

.btns {
    display: flex;
    justify-content: flex-end;
    padding: 10px;
    margin: 10px 0;
    border-radius: 5px;
    /* background-color: white; */
    /* border: 1px solid black; */
}

.block {
    margin: 10px 0;
}

.diaBtns {
    display: flex;
    justify-content: space-around;
    margin: 15px 0;
}

.diaInput {
    margin: 10px 0;
}
</style>
        